package grobit.wire

import java.nio.ByteBuffer

class BufferTests extends GroovyTestCase {

    void testBufferTake() {
        RequiredLengthBuffer underTest = new RequiredLengthBuffer(5)
        ByteBuffer fullBuf = ByteBuffer.wrap(new byte[5])

        assert underTest.remainingRequired() == 5
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 0
        assert underTest.full
        assert fullBuf.position() == fullBuf.limit()
    }

    void testBufferUnderTake() {
        RequiredLengthBuffer underTest = new RequiredLengthBuffer(5)
        ByteBuffer fullBuf = ByteBuffer.wrap(new byte[10])

        assert underTest.remainingRequired() == 5
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 0
        assert underTest.full
        assert fullBuf.position() == 5
        assert fullBuf.limit() == 10
    }

    void testBufferOverTake() {
        RequiredLengthBuffer underTest = new RequiredLengthBuffer(5)
        ByteBuffer fullBuf = ByteBuffer.wrap(new byte[2])

        assert underTest.remainingRequired() == 5
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 3
        assert !underTest.full
        assert fullBuf.position() == fullBuf.limit()
    }

    void testBufferRepeatTake() {
        RequiredLengthBuffer underTest = new RequiredLengthBuffer(6)
        ByteBuffer fullBuf = ByteBuffer.wrap(new byte[3])

        assert underTest.remainingRequired() == 6
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 3
        assert !underTest.full

        fullBuf = ByteBuffer.wrap(new byte[3])
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 0
        assert underTest.full
    }

    void testContent() {
        RequiredLengthBuffer underTest = new RequiredLengthBuffer(11)
        ByteBuffer fullBuf = ByteBuffer.wrap('Hello '.getBytes('ISO-8859-1'))

        assert underTest.remainingRequired() == 11
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 5
        assert !underTest.full

        fullBuf = ByteBuffer.wrap('World - I\'m Here'.getBytes('ISO-8859-1'))
        underTest.readFrom(fullBuf)
        assert underTest.remainingRequired() == 0
        assert underTest.full

        byte[] data = new byte[underTest.internBuffer.limit()]
        underTest.internBuffer.get(data)
        assert new String(data, 'ISO-8859-1') == 'Hello World'
    }
}
